/**
 * 判断是否为空
 */
function validatenull(val) {
  if (typeof val === "boolean") {
    return false;
  }
  if (typeof val === "number") {
    return false;
  }
  if (val instanceof Array) {
    if (val.length == 0) return true;
  } else if (val instanceof Object) {
    if (JSON.stringify(val) === "{}") return true;
  } else {
    if (
      val == "null" ||
      val == null ||
      val == "undefined" ||
      val == undefined ||
      val == ""
    )
      return true;
    return false;
  }
  return false;
}

// 表单序列化
export const serialize = data => {
  let list = [];
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`);
  });
  return list.join("&");
};
// 根据不同的屏幕宽度换算字体大小
export function transformFontSize(fontsize) {
  // 获取屏幕宽度
  const width = document.documentElement.clientWidth;
  const ratio = width / 750;
  console.log(parseInt(fontsize * ratio));
  // 取下整
  return parseInt(fontsize * ratio);
}

const keyName = "crm" + "-";
/**
 * 存储localStorage
 */
export const setStore = (params = {}) => {
  let { name, content, type } = params;
  name = keyName + name;
  let obj = {
    dataType: typeof content,
    content: content,
    type: type,
    datetime: new Date().getTime()
  };
  if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));
  else window.localStorage.setItem(name, JSON.stringify(obj));
};
/**
 * 获取localStorage
 */

export const getStore = (params = {}) => {
  let { name, debug } = params;
  name = keyName + name;
  let obj = {},
    content;
  obj = window.sessionStorage.getItem(name);
  if (validatenull(obj)) obj = window.localStorage.getItem(name);
  if (validatenull(obj)) return;
  try {
    obj = JSON.parse(obj);
  } catch {
    return obj;
  }
  if (debug) {
    return obj;
  }
  if (obj.dataType == "string") {
    content = obj.content;
  } else if (obj.dataType == "number") {
    content = Number(obj.content);
  } else if (obj.dataType == "boolean") {
    content = eval(obj.content);
  } else if (obj.dataType == "object") {
    content = obj.content;
  }
  return content;
};
/**
 * 删除localStorage
 */
export const removeStore = (params = {}) => {
  let { name, type } = params;
  name = keyName + name;
  if (type) {
    window.sessionStorage.removeItem(name);
  } else {
    window.localStorage.removeItem(name);
  }
};
// 此处调用安卓 打电话
export function callPhone(params) {
  let type = getAppType()
  console.log(type)
  if(type == 'android'){
    window.CrmJsInterface.call(params.phone, params.user_id, params.user_type);
  }
  if(type == 'ios'){
    window.webkit.messageHandlers.call.postMessage(params)
  }
}
/**
 * 获取app类型
 * @param
 * @return {String} app类型
 */
export function getAppType() {
  const u = window.navigator.userAgent;
  // console.log(u);
  if (
    u.indexOf("Android") > -1 ||
    u.indexOf("Linux") > -1 ||
    u.indexOf("Windows") > -1
  ) {
    return "android";
  }
  if (u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    return "ios";
  }
  return "";
}

/**
 * 防抖
 * @param
 * @return {String} 
 */
export function debounce(func, wait, immediate = false) {
  var timeout, result; // 自由变量空间
  // 真正要执行的函数
  return function() { // 二传手
      var context = this;
      var args = arguments;
      if (timeout) clearTimeout(timeout); // 清除定时器
      if (immediate) {
          var callNow = !timeout;//立即执行一次
          timeout = setTimeout(function() {
              timeout = null; // 释放
          }, wait);
          if (callNow) result = func.apply(context, args);
      } else {
          timeout = setTimeout(function() {
              result = func.apply(context, args);
          }, wait);
      }
      return result;
  };
}

// 调用原生拍照方法
export function openNativeCamera(){
  // 参数:quality 压缩质量 isCrop 是否裁剪
  var m={
    "quality": 30,
    "isCrop": false
  }
  window.callHandler("flutterOpenCamera", m, function(data) {
    console.log(data)
  })
}
//调用原生相册方法
export function openNativePhotos(){
  // 参数:quality 压缩质量 iscrop 是否裁剪
  // maximumImagescount 图片数量 最大值9 最小值1
  var m = {
    "quality": 30,
    "isCrop": false,
    "maximumImagesCount":1
  }
  window.callHandler("flutterImagePicker", m , function(data) {
    console.log(data);
  })
}

// 使用防抖函数
// debounce(getUserAction, 1000, true);

// 动态加载外部链接
export function loadJS(url) {
  return new Promise((resolve) => {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    // IE
    if (script.readyState) {
      script.onreadystatechange = () => {
        if (script.readyState == 'loaded'
          || script.readyState == 'complete') {
          script.onreadystatechange = null;
          resolve();
        }
      };
    } else {
      // 其他浏览器
      script.onload = function () {
        resolve();
      };
    }
    document.getElementsByTagName('head')[0].appendChild(script);
  })
}
import { Toast } from 'vant'
export function copyText(txt) {
    // 使用Clipboard API
    if (navigator.clipboard) {
        navigator.clipboard.writeText(txt).then(() => {
            Toast.success('复制成功！');
        }).catch(err => {
            console.error("复制失败:", err);
            Toast.fail("复制失败:"+err);
            fallbackCopyText(); // 如果Clipboard API失败，使用回退方案
        });
    } else {
        // Clipboard API不可用，使用回退方案
        fallbackCopyText(txt);
    }
}
export function fallbackCopyText(txt) {
    // 创建临时的textarea元素
    const tempTextArea = document.createElement("textarea");
    tempTextArea.value = txt;
    // 防止页面布局被临时元素影响
    tempTextArea.style.position = "fixed"; // 固定在视口
    tempTextArea.style.left = "-9999px"; // 隐藏到视口外
    // 将textarea添加到body中
    document.body.appendChild(tempTextArea);
    // 选择文本
    tempTextArea.select();
    // 执行复制操作
    try {
        const successful = document.execCommand("copy");
        const msg = successful ? "successful" : "unsuccessful";
        console.log("Fallback: Copying text command was " + msg);
        Toast.success("复制成功");
    } catch (err) {
        console.error("Fallback: Oops, unable to copy", err);
        Toast.fail("复制失败");
    }
    // 移除临时元素
    document.body.removeChild(tempTextArea);
}
